import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

class UserInfo {
  final Map<String, dynamic> _attributes = {};

  dynamic operator [](String key) => _attributes[key];
  void operator []=(String key, dynamic value) => _attributes[key] = value;

  Map<String, dynamic> get attributes => _attributes;

  UserInfo();

  UserInfo.fromJson(Map<String, dynamic> json) {
    _attributes.addAll(json);
  }

  Map<String, dynamic> toJson() => _attributes;
}

class AppState with ChangeNotifier {
  UserInfo _userInfo = UserInfo();
  String _token = 'false';

  UserInfo get userInfo => _userInfo;
  String get token => _token;

  AppState() {
    loadFromPrefs();
  }

  void setUserInfoAttribute(String key, dynamic value) {
    _userInfo[key] = value;
    _saveToPrefs();
    notifyListeners();
  }

  void setUserInfo(UserInfo data) {
    _userInfo = data;
    _saveToPrefs();
    notifyListeners();
  }

  void setToken(String token) {
    _token = token;
    _saveToPrefs();
    notifyListeners();
  }

  void clear() {
    _userInfo = UserInfo();
    _token = '';
    _saveToPrefs();
    notifyListeners();
  }

  Future<void> loadFromPrefs() async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String? userInfoString = prefs.getString('userInfo');
      String? token = prefs.getString('token');

      _userInfo = UserInfo.fromJson(jsonDecode(userInfoString!));

      _token = token!;

      notifyListeners();
    } catch (e) {
      // 处理异常，例如记录日志或显示错误信息
      print('Failed to load preferences: $e');
    }
  }

  void _saveToPrefs() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString('userInfo', jsonEncode(_userInfo.toJson()));
    prefs.setString('token', _token);
  }
}
